//
//  DSBaseController.swift
//  DSP
//
//  Created by tucici on 2024/6/23.
//

import UIKit
import Charts
import TCCKit
///更新图表通知
let updateChartStatus = "updateChartStatus"
///更新全局通道通知
let updateChannelManager = "updateChannelManager"
///更新Group通道通知
let updateResetDSP = "updateResetDSP"
class DSBaseController : DSViewController {
    private var limitArray = Array(repeating: ChartLimitLine(), count: 3)
    override func viewDidLoad() {
        super.viewDidLoad()
        initData()
        updateData()
    }
    
    ///数据更新
    @objc func updateData(){
        
        ///输入人形锁后 ，group通道才可以用
        _ = groupArray.map{
            $0.enable = !APP.pwd.isEmpty
        }
        
        ///更新数据，并保存到本地
        let copy = APP.CHM.copy() as! ChannelManager
        let date = Date.date(formatter: "yyyy-MM-dd HH:mm:ss")
        if copy.name == ""{
            copy.name = date
            APP.CHM.name = date
        }
        copy.date = date
        //RealmHelper.updateObject(object: copy)
        
        NotifyTool.post(updateChartStatus)///更新图表
    }
    
    ///数据初始化
    override func initData() {
        super.initData()
        ///初始化图标，默认首页不选中任何通道
        APP.CHM.ch1.select = className != SumViewController.className
        chartLineColor = lineColors[0].color()///图表折线颜色默认是通道1的颜色
        frency_arr = Array(repeating: 0, count: Int(kUIScreenWidth) - 35)///图表数据默认是通道1的数据
    }
    func sendData(){}
    
    ///页面每次刷新选中的通道状态
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        refreshChannelStatus()
    }
    
    ///刷新通道状态，每次页面都回到本页记住选中的通道的状态
    private func refreshChannelStatus(){
        if [SumViewController.className,  CrossViewController.className,
            GainViewController.className, EQViewController.className].contains(className) == false{return}
        //if select_ch_index >= APP.CHM.array.count {return}
        for i in 0..<APP.CHM.array.count{
            let ch = APP.CHM.array[i]
            ch.select = select_ch_index == i
            //            if ch.enable{continue}
            //            ch.enable = className != EQViewController.className
        }
        for j in 0..<groupArray.count{
            if select_group_index == 100 {continue}
            let group = groupArray[select_group_index]
            if select_group_index != j || group.select == false{continue}
            group.select = true
        }
    }
    
    ///更新图表
    @objc private func updateChartView(){
        let tabvc = APP.window?.rootViewController as? DSTabBarViewController
        let sumvc = (tabvc?.viewControllers![0] as? DSNavigationController)?.topViewController as! SumViewController
        let crossvc = (tabvc?.viewControllers![1] as? DSNavigationController)?.topViewController as! CrossViewController
        let gainvc = (tabvc?.viewControllers![2] as? DSNavigationController)?.topViewController as! GainViewController
        let eqvc = (tabvc?.viewControllers![3] as? DSNavigationController)?.topViewController as! EQViewController
        var ch : ChannelModel!
        
        switch self{
        case sumvc:
            chartLineColor = lineColors[eqvc.select_ch_index].color()
            ch = APP.CHM.array[eqvc.select_ch_index]
        case crossvc,
        eqvc:
            chartLineColor = lineColors[select_ch_index].color()
            ch = APP.CHM.array[select_ch_index]
        case gainvc:
            chartLineColor = lineColors[crossvc.select_ch_index].color()
            ch = APP.CHM.array[crossvc.select_ch_index]
        default:
            break
        }
        
        frency_arr = draw()
        func draw()->[Double]{
            var result = Array(repeating: Double(0), count: Int(kUIScreenWidth) - 35)
            
            ///1, 计算该通道信号的增益
            for sign in ch.signArray{
                var array = Array(repeating: Double(0), count: Int(kUIScreenWidth) - 35)
                EQUtil.eq(quality: CGFloat(sign.quality), gain: CGFloat(sign.gain), frency: CGFloat(sign.frency), in: &array)
                result = zip(result, array).map{$0 + ($1 * 20)}
            }
            
            ///2, 计算该通道的高通
            var temp1 = Array(repeating: Double(0), count: Int(kUIScreenWidth) - 35)
            EQUtil.filter(f: Double(ch.highPass.cutFrency), oct_type: ch.highPass.oct_type, ishpass: true, bypass: ch.highPass.bypass, array: &temp1)
            result = zip(result, temp1).map{$0 + ($1 * 0.5555556 * 25)}
            
            ///3, 计算该通道的低通
            var temp2 = Array(repeating: Double(0), count: Int(kUIScreenWidth) - 35)
            EQUtil.filter(f: Double(ch.lowPass.cutFrency), oct_type:ch.lowPass.oct_type, ishpass: false, bypass: ch.lowPass.bypass,array: &temp2)
            result = zip(result, temp2).map{$0 + ($1 * 0.5555556 * 25)}
            
            return result
        }
    }
    
    @objc func resetAction(){
        groupArray = [GroupModel(array: Array(APP.CHM.array[0...1]),num: 0),
                      GroupModel(array: Array(APP.CHM.array[2...3]),num: 1),
                      GroupModel(array: Array(APP.CHM.array[4...5]),num: 2),
                      GroupModel(array: Array(APP.CHM.array[6...7]),num: 3)]
        updateData()
    }
    
    ///记录选中的group的下标
    var select_group_index : Int = 100
    ///记录选中的channel的下标
    var select_ch_index : Int = 0
    
    ///需要划线的频率
    private (set) var frency_arr_show : [Int] = [20, 113, 114, 876, 880, 881, 16137, 16262, 16392, 22000]
    private var chartLineColor : UIColor!
    private var lineColors = ["#C5283B", "#0000FF", "#00FF00", "#00FFFF", "#FFFF00", "#FFFFFF", "#FF00FF", "#D2691E"]
    ///绘图的k线图数据
    var frency_arr = [Double](){
        didSet{
            chartView.array = frency_arr.map{CGFloat($0)}
            chartView.chatView.xAxis.setLabelCount(frency_arr.count, force: true)
        }
    }
    
    /// groupModel 通道
    lazy var groupArray : [GroupModel] = {
        return [GroupModel(array: Array(APP.CHM.array[0...1]),num: 0),
                GroupModel(array: Array(APP.CHM.array[2...3]),num: 1),
                GroupModel(array: Array(APP.CHM.array[4...5]),num: 2),
                GroupModel(array: Array(APP.CHM.array[6...7]),num: 3)]
    }()
    
    lazy var chartView : ChartView = {
        let view = ChartView(frame: CGRect(x: 0.0, y: 0.0, width: kUIScreenWidth, height: floor(k_h(120))))
        view.setRadius = 1
        view.setLineWidth = 1.5
        view.validValue = -20
        view.delegate = self
        view.snp.makeConstraints { make in
            make.size.equalTo(view.frame.size)
        }
        return view
    }()
}

//MARK: - 图标代理 CharViewDelegate
extension DSBaseController : ChartDelegate{
    func chartValueSelected(_ chartView: Charts.ChartViewBase, entry: Charts.ChartDataEntry, highlight: Charts.Highlight) {
        //print("选中的 =======x=\(entry.x)  y=\(entry.y)")
    }
    
    func chartDataSet(_ datas: [ChartDataEntryBase]) -> ChartData {
        guard let entries = datas as? [ChartDataEntry] else {return chartView.chatView.data ?? ChartData()}
        let data = LineChartData()
        let set = LineChartDataSet(entries: entries)
        set.setColor(chartLineColor)
        set.lineWidth = 1.5
        set.axisDependency = .left
        set.mode = .cubicBezier
        set.drawCirclesEnabled = false
        set.drawValuesEnabled = false
        data.append(set)
        //data.setValueFormatter(kIValueFormatter())
        return data
    }
    
    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        if let leftAxis = axis as? YAxis{
            return "\(Int(value))" + (Int(value) == 0 ? "dB" : "")
        }else if let _ = axis as? XAxis{
            let i = EQUtil.deInt(v: Int(value)+1, inMax:Int(kUIScreenWidth - 35) , inMin: 1)
            //print("===== = \(Int(i))  =  \(value)")
            if frency_arr_show.contains(Int(i)) == false{return ""}
            switch Int(i){
            case 20:
                return "20"
            case 100..<150:
                if abs(limitArray[0].limit - value) > 10{
                    limitArray[0] = chartView.addCustomLine(chartView.chatView.xAxis, CGFloat(value))
                }
                return "115"
            case 850..<1150:
                if abs(limitArray[1].limit - value) > 10{
                    limitArray[1] = chartView.addCustomLine(chartView.chatView.xAxis, CGFloat(value))
                }
                return "1K"
            case 16000..<17000:
                if abs(limitArray[2].limit - value) > 10{
                    limitArray[2] = chartView.addCustomLine(chartView.chatView.xAxis, CGFloat(value))
                }
                return "16K"
            case 22000:
                return "22K"
            default:
                return ""
            }
        }
        return ""
    }
    
}

//MARK: - 通知
extension DSBaseController{
    @objc override func addNotify(){
        super.addNotify()
        NotifyTool.add(self, #selector(updateChartView),updateChartStatus)
        NotifyTool.add(self, #selector(updateData),updateChannelManager)
        NotifyTool.add(self, #selector(resetAction),updateResetDSP)
        
    }
}
